<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('multilingual.barcodeSplit')"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'">
				<!-- 扫描条码部分 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('multilingual.mergeBarcodeInfo')}}
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{$t('distributedEnter.materialCoded')}}
						</text>
						<!-- <input type="text" focus placeholder="请输入文本" /> -->
						<uni-easyinput type="search" :focus="data.isfocus" class="uni-mt-5" suffixIcon="scan" v-model="data.barcode"
							:placeholder="$t('multilingual.scanBarcodeInfo')" @confirm="confirm('barcode')"
							@iconClick="iconClick($event,'barcode')" @focus="getFocus('barcode')"></uni-easyinput>
					</view>
					<view class="gui-form-item gui-border-b gui-flex gui-align-items-center gui-space-between"
						style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color" style="opacity: 0;">*</text>
							{{$t('pageTranslation.splitToExisting')}}：
						</text>
						<switch :checked="data.isChecked" :disabled="Object.keys(data.barcodeInfo).length === 0"
							style="transform:scale(0.7)" @change="switchChange" />
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;" v-if="data.isSplitNowBarcode">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color" style="opacity: 0;">*</text>
							{{$t('multilingual.existingBarcode')}}
						</text>
						<uni-easyinput type="search" class="uni-mt-5" suffixIcon="scan" v-model="data.splitBarcode"
							:placeholder="$t('pageTranslation.spiltExistiingBarcode')"
							@confirm="confirm('splitBarcode')" @iconClick="iconClick($event,'splitBarcode')"
							@focus="getFocus('splitBarcode')">
						</uni-easyinput>
					</view>
				</view>
				<!-- card区域 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll element-auto">
					<view style="height: 15rpx"></view>
					<view class="card-boxCustom" style="margin-bottom: 0;"
						v-if="Object.keys(data.barcodeInfo).length !== 0">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{$t('multilingual.barcodeScanning')}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialName')}}：</text>
								{{data.barcodeInfo.materialName}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialCoded')}}：</text>
								{{data.barcodeInfo.barcode}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialCode')}}：</text>
								{{data.barcodeInfo.materialCode}}
							</view>
							<view class="custom-card-itemOne" v-if="data.barcodeInfo.materialSpec != ' '">
								<text class="body-item-title">{{$t('distributedEnter.materialSpec')}}：</text>
								{{data.barcodeInfo.materialSpec}}
							</view>
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{$t('distributedEnter.qty')}}：</text>
									{{data.barcodeInfo.currentQty}}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{$t('distributedEnter.uom')}}：</text>
									{{data.barcodeInfo.unit}}
								</view>
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('translationImage.currentWarehouse')}}：</text>
								{{data.barcodeInfo.warehouseCode}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('translationImage.currentLocation')}}：</text>
								{{data.barcodeInfo.locationName}}
							</view>
							<view class="custom-card-itemOne" style="padding:20rpx 0;">
								<text class="item-info-title" style="padding-right: 40rpx;">
									{{$t('translationImage.resolutionQty')}}
								</text>
								<uni-easyinput class="uni-mt-5" v-model="data.codeNumber" @blur="codeNumberBlur"
									type="number" :placeholder="$t('translationImage.resolutionBarcodeQty')">
								</uni-easyinput>
							</view>
						</view>
					</view>
					<view style="height: 15rpx"></view>
					<view class="card-boxCustom" style="margin-bottom: 0;"
						v-if="Object.keys(data.newBarcodeInfo).length !== 0">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{$t('materials.existingBarcodeInformation')}}
								<!-- {{$t('multilingual.newBarcodeInfo')}} -->
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialName')}}：</text>
								{{data.newBarcodeInfo.materialName}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialCoded')}}：</text>
								{{data.newBarcodeInfo.barcode}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('distributedEnter.materialCode')}}：</text>
								{{data.newBarcodeInfo.materialCode}}
							</view>
							<view class="custom-card-itemOne" v-if="data.newBarcodeInfo.materialSpec != ' '">
								<text class="body-item-title">{{$t('distributedEnter.materialSpec')}}：</text>
								{{data.newBarcodeInfo.materialSpec}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('translationImage.currentWarehouse')}}：</text>
								{{data.newBarcodeInfo.warehouseCode}}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{$t('translationImage.currentLocation')}}：</text>
								{{data.newBarcodeInfo.locationName}}
							</view>
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{$t('distributedEnter.qty')}}：</text>
									{{data.newBarcodeInfo.currentQty}}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{$t('distributedEnter.uom')}}：</text>
									{{data.newBarcodeInfo.unit}}
								</view>
							</view>
							<view class="custom-card-itemOne gui-flex gui-justify-content-end">
								<view class="print-class" @click="printsLabelsFn">
									{{$t('multilingual.printBarcode')}}
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{$t('calendar.confirm')}}
					</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import {
	ref,
	reactive,
	onMounted,
	computed
} from 'vue'
import {
	selectWmsBarcodeInfoWms,
	splitBarcodeApi,
	printsLabels1
} from '@/api/api.js'
import { BIGBARCODER_PRINT } from '@/constant/index.js'
import pdaScan from '@/hooks/pdaScan.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN,OPERATION_PRINT } from '@/constant/index.js'
import {  PRINT_BASE_URL } from "@/constant/config.js"
import { onShow } from '@dcloudio/uni-app';
import {
	useStore
} from "vuex";

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

//打印机地址
let printUrl=PRINT_BASE_URL

const { scan } = pdaScan()
let store = useStore();
let data = reactive({
	isfocus:false,
	isChecked: false,// 是否选中
	splitBarcode: '', //接收条码号
	barcode: '', // 拆分条码号
	codeNumber: null,
	isSplitNowBarcode: false,
	inputType: '',
	barcodeInfo: {}, //拆分条码号信息
	splitBarcodeInfo: {},//接收拆分条码号信息
	newBarcodeInfo: {}, //新条码号信息
	defaultValue: '', //打印机名字
})
// 页面底部高度
const navHeight = computed(() => {
	return store.state.navHeight
})

onShow(()=>{
	data.defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (data.defaultValue == '') {
		// uni.showModal({
		// 	content: t('JsInternational.plsPrinter'),
		// 	showCancel: false,
		// });
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText:t('pageTranslation.toSet'),
			success: function (res) {
					if (res.confirm) {
						 uni.navigateTo({
						 	url:'/pages/setting/printer'
						 })
					} else if (res.cancel) {
						
					}
				}
		});
	}
})
onMounted(() => {
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	setTimeout(() => {  
		data.isfocus = true
	}, 1000)
})
// 打印
const printsLabelsFn = () => {
	console.log(data.newBarcodeInfo, 'data.newBarcodeInfodata.newBarcodeInfo')
	let parmase = {
		barCode: data.newBarcodeInfo.barcode,
		materialCode: data.newBarcodeInfo.materialCode,
		materialName: data.newBarcodeInfo.materialName,
		specification: data.newBarcodeInfo.materialSpec,
		LocationCode:data.newBarcodeInfo.locationCode,
		produceDate: data.newBarcodeInfo.produceDate ? data.newBarcodeInfo.produceDate.slice(0, 10) : '', // 生产日期
		hostid: data.newBarcodeInfo.equipmentCode || '', //机台
		qty: data.newBarcodeInfo.initQty,
		uuit: data.newBarcodeInfo.unit, //单位
		printerName: data.defaultValue, //打印机名字
		splitStatus:'拆'
	}
	uni.showLoading({
		title: t('materials.connecting')
	});
	printsLabels1(parmase).then(res => {
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码拆分'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res, 'reessss')
		if (res.status == 200) {
			
			uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	}).catch(() => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = '无'
			let operationPicture = '条码拆分'
			let callInterface = printUrl+"/print/RawMaterialBarCodePrint"
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: 408,//返回状态
				errorMessage: '请求超时',//错误信息
				isPass: 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		uni.showToast({ title: t('materials.printingFailed'), icon: "none" });
		uni.hideLoading();
	})
}
// 提交条码拆分信息
const submit = () => {
	if (data.barcode == '') {
		return uni.showToast({ title: t('JsInternational.splitBarcode'), icon: "none" });
	}
	if (JSON.stringify(data.barcodeInfo) == '{}') {
		return uni.showToast({ title: t('JsInternational.searchBarcode'), icon: "none" });
	}
	if (data.codeNumber == '') {
		return uni.showToast({ title: t('JsInternational.splitQty'), icon: "none" });
	}
	if (data.codeNumber > data.barcodeInfo.currentQty) {
		return uni.showToast({ title: t('JsInternational.greaterQty'), icon: "none" });
	}
	if (Number(data.codeNumber) == 0) {
		return uni.showToast({ title: t('materials.splitsNeedsTo'), icon: "none" });
	}
	if (data.isSplitNowBarcode && !data.splitBarcode) {
		return uni.showToast({ title: t('JsInternational.receiptBarcode'), icon: "none" });
	}
	if (data.barcode == data.splitBarcode) {
		uni.showToast({ title: t('materials.existingBarcodeAnd'), icon: "none" });
		return
	}
	uni.showModal({
		content: t('JsInternational.submitConfirm'),
		success: (res) => {
			if (res.confirm) {
				submitInterface()
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
// 提交请求后端接口
const submitInterface = () => {
	let parmes = {
		id: data.barcodeInfo.id,
		currentQty: data.codeNumber,
		splitOld: data.isSplitNowBarcode,
		oldBarcode: data.splitBarcode
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	splitBarcodeApi(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码拆分'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			data.newBarcodeInfo = res.data
			data.barcodeInfo = {}
			data.isChecked = false
			data.barcode = ''
			data.splitBarcode = ''
			data.isSplitNowBarcode = false
			data.codeNumber = null
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
// 获得焦点
const getFocus = (type) => {
	console.log(type)
	data.inputType = type;
}
// 条数输入失去焦点
const codeNumberBlur = (e) => {
	const { value } = e.detail
	console.log(value)
	if (Number(value) <= 0) {
		uni.showToast({ title: t('materials.splitsNeedsTo'), icon: "none" });
		data.codeNumber = null
		return
	}
}
// 用户调起相机扫码
const iconClick = async (type, inputType) => {
	console.log(type)
	if (type === 'suffix') {
		data.inputType = inputType;
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = (type) => {
	data.inputType = type;
	let code = type == 'barcode' ? data.barcode : data.splitBarcode
	getCode(code, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	if (data.inputType == 'barcode') {
		data.barcode = code
	} else {
		data.splitBarcode = code
	}
	if (data.barcode == data.splitBarcode) {
		uni.showToast({ title: t('materials.existingBarcodeAnd'), icon: "none" });
		return
	}
	data.checked = false
	data.scanValue = code
	// data.isChecked = false
	// data.isSplitNowBarcode = false
	console.log(`拿到code,code为${code},type类型为${type}`)
	let parmes = {
		barcode: code,
		selectType: 'splitBarcode'
	}
	selectWmsBarcodeInfoWms(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码拆分'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.newBarcodeInfo = {}
			console.log(data.inputType, 'data.inputType')
			if (data.inputType == 'barcode') {
				data.barcodeInfo = res.data;
			} else if (data.inputType == 'splitBarcode') {
				if (data.barcodeInfo.materialCode !== res.data.materialCode) return uni.showToast({ title: t('pageTranslation.materialSameForBoth'), icon: "none" });
				data.splitBarcodeInfo = res.data;
			}
			//这里不能清空
			data.inputType = 'barcode'
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
// 开关切换
const switchChange = (e) => {
	console.log(e.detail.value)
	data.isChecked = e.detail.value
	data.isSplitNowBarcode = e.detail.value
	if (!e.detail.value) {
		data.splitBarcode = ''
	}
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.print-class {
	display: inline-block;
	padding: 10rpx 20rpx;
	background-color: chartreuse;
	color: #fff;
	border-radius: 8rpx;
	background: $uni-color-teal;
}
</style>
